<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle">
      <span class="placeholder" v-if="!address.fullLocation">{{fullLocation ||'请选择配送地址'}}</span>
      <span class="value" v-else>{{address.fullLocation}}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="isShow">
      <div class="loading" v-if="isLoading"></div>
      <template v-else>
        <span class="ellipsis" v-for="item in list" :key="item.code" @click="gerAddress(item)">
          {{ item.name }}
        </span>
      </template>
    </div>
  </div>
</template>

<script>
import { computed, reactive, ref, watch } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: '请选择配送地址'
    }
  },
  setup (props, { emit }) {
    const isShow = ref(false)
    const target = ref(null)
    const cityData = ref([])
    const isLoading = ref(false)

    // 添加收货地址  /member/address
    //  provinceCode 所在省份编码
    // cityCode 所在城市编码
    // countyCode 所在区/县编码
    const address = reactive({
      provinceCode: '', // 所在省份编码
      provinceName: '', // 所在省份名字
      cityCode: '', // 所在城市编码
      cityName: '',
      countyCode: '', // 所在区/县编码
      countyName: '',
      fullLocation: '' // 完整地址，包括省市区3级的文字
    })

    // 🔔按照添加收货地址的接口文档参数要求准备数据
    // code 用于后端请求，name 是用于前端展示

    watch(() => props.fullLocation, (val) => {
      if (val === '') {
        for (const key in address) {
          address[key] = ''
        }
      } else {
        address.fullLocation = val
      }
    }, { immediate: true })

    // 获取城市数据，考虑到全国所有城市数据量比较大，所以我们做缓存
    // 因为函数内部有两种情况：
    //    直接读取缓存(window对象上)
    //    网络请求的
    const getCityData = async () => {
      if (!window.cityData) {
        const { data } = await axios(
          'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
        )
        // console.log(data)
        if (data) {
          window.cityData = data
        }
      }
      return window.cityData
    }

    const toggle = () => {
      isShow.value === true ? hide() : show()
    }

    const show = async () => {
      isShow.value = true
      isLoading.value = true
      // async 函数调用后，返回的是一个 Promise 对象，所以需要通过 then 或者 await 获取值
      cityData.value = await getCityData()
      isLoading.value = false
      //   console.log(cityData.value)

      // 打开面板表示用户需要重新选择地址，遍历清空所有旧地址数据
      for (const key in address) {
        address[key] = ''
      }
    }

    const hide = () => {
      isShow.value = false
    }

    onClickOutside(target, (e) => {
      //   console.log(e)
      // isShow.value = false
      hide()
    })

    const gerAddress = (theItem) => {
    //   console.log(theItem)
      if (theItem.level === 0) {
        //   省
        address.provinceCode = theItem.code
        address.provinceName = theItem.name
      } else if (theItem.level === 1) {
        // 市
        address.cityCode = theItem.code
        address.cityName = theItem.name
      } else if (theItem.level === 2) {
        // 区/县
        address.countyCode = theItem.code
        address.countyName = theItem.name

        // 已经获取完数据
        address.fullLocation = `${address.provinceName} ${address.cityName} ${address.countyName}`

        // 最后一级，需要隐藏面板
        hide()

        // 触发父组件的自定义事件，允许父组件获取当前子组件选中的地址
        emit('change', address)
      }
    //   console.log(address)
    }

    // 计算一个用于给用户选择的列表
    const list = computed(() => {
      // 默认情况下，显示省
      let temp = cityData.value
      // 根据省的编码获取到 市 的列表
      if (address.provinceCode) {
        temp = temp.find(item => {
          return item.code === address.provinceCode
        }).areaList
      }
      if (address.cityCode) {
        temp = temp.find(item => {
          return item.code === address.cityCode
        }).areaList
      }
      return temp
    })

    return { isShow, toggle, target, list, isLoading, gerAddress, address }
  }
}
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
    .loading {
      height: 290px;
      width: 100%;
      background: url(~@/assets/images/loading.gif) no-repeat center;
    }
  }
}
</style>
